package core.dao;

import core.entity.Post;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by Christian Waickem on 9/29/2014.
 */
@Repository
public class PostDAO {

    @PersistenceContext
    EntityManager em;

    public List<Post> getAllPosts() {
        return em.createQuery("SELECT p FROM Post p", Post.class)
                .getResultList();
    }

    public List<Post> getAllShortContent() {
        return em.createNativeQuery("SELECT id, substring(content,1,200) as content, create_date, title, category_id, created_by_user_id FROM post", Post.class).getResultList();
    }

    public Post findPostById(long id) {
        return em.find(Post.class, id);
    }

    public List<Post> searchPostsByString(String searchString){
        return em.createNativeQuery("SELECT id, substring(content,1,200) as content, create_date, title, category_id, created_by_user_id from post WHERE title like '%"+searchString+"%'", Post.class).getResultList();
    }

    public List<Post> searchPostsByContent(String searchString){
        return em.createNativeQuery("SELECT id, substring(content,1,200) as content, create_date, title, category_id, created_by_user_id from post WHERE content like '%"+searchString+"%'", Post.class).getResultList();
    }
}


